'use strict';

angular.module('app')
    .controller('updateController', ['$scope', '$rootScope', '$state', '$timeout',
        function ($scope, $rootScope, $state, $timeout) {
            var title = "";


            if ($state.includes('**.hotSearch.update')) {
                title = "修改词汇";
                var id = $state.params.id;
                activate(id);
                $scope.isDisabled = false;
            } else if ($state.includes('**.hotSearch.add')) {
                title = "添加词汇";
                setTimeout(function(){
                    !$rootScope.$$phase && $scope.$apply();
                },300);
            }

            $scope.title = $rootScope.title = title;
            $scope.loading = true;


            // 提交数据
            $scope.submit = function(){
                $scope.loading = true;

                if(!$('#searchContent').val()){
                    $scope.alertModal({'content':'请输入热搜词汇'});
                    return;
                }
                if($('#searchContent').val().length>8){
                    $scope.alertModal({'content':'热搜词汇不允许超过8个字符'});
                    return;
                }
                saveData();
            };

            function saveData(){
                var m = $scope.record;
                console.log(m);
                if(m){
                    $scope.isDisabled = true;//提交disabled
                    $.ajax({
                        url : $scope.record.hotNo ? $scope.app.project_name + '/hotSearch/update' : $scope.app.project_name + '/hotSearch/add',
                        data: m
                    }).then(callback);
                }
                function callback(result){
                    if(result.httpCode ==200){
                        $scope.alertModal({"content":"操作成功"});
                        $timeout(function(){
                            $state.go('main.communityConfig.hotSearch.list');
                        },2000);
                    }else{
                        $scope.alertModal({"content":"操作失败"});
                        $scope.isDisabled = false;
                    }
                    $scope.loading = false;
                }
            }


            // 初始化页面
            function activate(hotNo) {
                $scope.loading = true;
                $.ajax({
                    url : $scope.app.project_name + '/hotSearch/detail',
                    data: {'hotNo': hotNo}
                }).then(function(result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                        $scope.record = result.data;
                    } else {
                        $scope.msg = result.msg;
                    }
                    $scope.$apply();
                });
            }

        }]);